package com.jerry.wschat.web.websocket;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @author Jerry.Wu
 * @description:
 * @date 2018/9/12 14:55
 */
@Slf4j
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class WebSocketServer {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 打开连接时触发
     * @param userId
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("userId") Integer userId, Session session) {
        logger.info("Websocket Start Connecting: {}", userId);
        WebSocketUtils.addOnlineCount();
        WebSocketUtils.put(userId, session);
    }

    /**
     * 收到客户端消息时触发
     * @param userId
     * @param message
     * @return
     */
    @OnMessage
    public String onMessage(@PathParam("userId") Integer userId, String message) {
        try {
            if (!WebSocketUtils.hasConnection(userId)) {
                throw new NullPointerException("websocket connection does not exist for user " + userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "sorry, exception is : " + e.getMessage();
        }
        return "Your msg is : " + message;
    }

    /**
     * 异常时触发
     * @param userId
     * @param session
     */
    @OnError
    public void onError(@PathParam("userId") Integer userId, Throwable throwable, Session session) {
        logger.info("Websocket Connection Exception:{}", userId);
        logger.info(throwable.getMessage(), throwable);
		WebSocketUtils.remove(userId, session);
    }

    /**
     * 关闭连接时触发
     * @param userId
     * @param session
     */
    @OnClose
    public void onClose(@PathParam("userId") Integer userId, Session session) {
        logger.info("Websocket Close Connection:", userId);
        WebSocketUtils.remove(userId, session);
    }

}
